<template>
  <div class="page-cardBagSetting views-container">
    <div class="wlm-table">
      <div class="wlm-dialog-content">
        <el-form
          :model="cDataToSave"
          :rules="cFormRules"
          ref="cardBagSetting"
          size="small"
          label-width="130px"
          class="retail-form"
          label-position="right"
        >
          <!-- 卡包分类 -->
          <el-form-item label="卡包分类" prop="card_class_id">
            <el-select
              filterable
              v-model="formFormatData.formData.card_class_id"
              placeholder="请选择卡包分类"
            >
              <el-option
                v-for="item in cardBagCateList"
                :key="item.card_class_id"
                :label="item.name"
                :value="item.card_class_id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 卡包分类 end -->
          <!-- 卡包logo图 -->
          <el-form-item label="卡包logo图" prop="image_id">
            <choose-files
              ref="chooseLogoId"
              :config="chooseLogoIdformConfig"
              :changeEvt="formFormatFiltersChange"
            ></choose-files>
            <div class="form-help">建议尺寸：大小0.5M以下,建议尺寸690×300px</div>
          </el-form-item>
          <!-- 卡包logo图 end -->
          <!-- 背景图片 -->
          <el-form-item label="背景图片" prop="image_id">
            <choose-files
              ref="chooseImageId"
              :config="chooseImageIdformConfig"
              :changeEvt="formFormatFiltersChange"
            ></choose-files>
            <div class="form-help">建议尺寸：大小0.5M以下,建议尺寸690×300px</div>
          </el-form-item>
          <!-- 背景图片 end -->
          <!-- 次数类型 -->
          <el-form-item label="次数类型">
            <el-radio-group v-model="formFormatData.formData.type">
              <el-radio :label="1">固定次数</el-radio>
              <el-radio :label="2">任意次数</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 次数类型 end -->
          <!-- 可核销次数 -->
          <el-form-item v-if="formFormatData.formData.type == 1" label="可核销次数" prop="number">
            <el-input-number
              v-model="formFormatData.formData.number"
              :controls="false"
              :precision="0"
              :min="0"
            ></el-input-number>
          </el-form-item>
          <!-- 可核销次数 end -->
          <!-- 卡包名称 -->
          <el-form-item label="卡包名称" prop="title">
            <el-input
              v-model.trim="formFormatData.formData.title"
              placeholder="请输入卡包名称"
              style="width: 60%"
            ></el-input>
          </el-form-item>
          <!-- 卡包名称 end -->
          <!-- 使用限制 -->
          <el-form-item label="使用限制" >
            <el-row :gutter="4">
              <el-col style="width: auto">每</el-col>
              <el-col style="width: auto">
                <el-form-item prop="day">
                  <el-input-number
                    style="width: 100px"
                    v-model="formFormatData.formData.day"
                    :controls="false"
                    :min="0"
                    :precision="0"
                    :disabled="isEdit"
                  />
                </el-form-item>
              </el-col>
              <el-col style="width: auto">天</el-col>
              <el-col style="width: auto">最多使用</el-col>
              <el-col style="width: auto">
                <el-form-item prop="day_number">
                  <el-input-number
                    style="width: 100px"
                    v-model="formFormatData.formData.day_number"
                    :controls="false"
                    :min="0"
                    :precision="0"
                    :disabled="isEdit"
                  />
                </el-form-item>
              </el-col>
              <el-col style="width: auto">次</el-col>
              <el-col style="width: auto">注：起算日期为购买当天。例：30天释放10次，表示30天内最多使用10次。都填0表示无限制。</el-col>
            </el-row>
          </el-form-item>
          <!-- 使用限制 end -->
          <!-- 未达限制是否扣次 -->
          <el-form-item label="未达限制是否扣次">
            <el-row :gutter="4">
              <el-col style="width: auto">
                <el-switch
                  v-model="formFormatData.formData.is_sub"
                  :active-value="1"
                  :inactive-value="2"
                ></el-switch>
              </el-col>
              <el-col style="width: auto">例：30天释放10次，若30天未使用到10次，依旧扣除10次</el-col>
            </el-row>
          </el-form-item>
          <!-- 未达限制是否扣次 end -->
          <!-- 单次售卖价格 -->
          <el-form-item label="单次售卖价格" prop="unit_price">
            <el-row :gutter="4">
              <el-col style="width: auto">
                <el-input-number
                  style="width: 100px"
                  v-model="formFormatData.formData.unit_price"
                  :controls="false"
                  :min="0"
                  :precision="2"
                  :disabled="isEdit"
                />
              </el-col>
              <el-col style="width: auto">元</el-col>
              <el-col style="width: auto">注：用户支付金额 = 单次售卖价格 × 购买的次数</el-col>
            </el-row>
          </el-form-item>
          <!-- 单次售卖价格 end -->
          <!-- 卡券详情 -->
          <el-form-item label="卡券详情" prop="content">
            <ueditor
              :ueditorChange="ueditorChange"
              :ueditorList="ueditorList"
              :bindIndex="1"
              :defaultMsg="formFormatData.formData.content"
              :config="{ initialFrameWidth: null, initialFrameHeight: 350 }"
              ref="by_know"
            ></ueditor>
          </el-form-item>
          <!-- 卡券详情 end -->
          <!-- 可核销商家分类 -->
          <el-form-item label="可核销商家分类" prop="business">
            <el-select
              multiple
              filterable
              v-model="formFormatData.formData.business_class_ids"
              placeholder="请选择卡包分类"
              style="width: 60%"
            >
              <el-option
                v-for="item in cusinessCateList"
                :key="''+item.sort_id"
                :label="item.sort_name"
                :value="''+item.sort_id"
              ></el-option>
            </el-select>
            <el-table
              style="width: 100%; margin-top: 20px"
              :data="storeList"
              height="300"
              :default-sort="{ prop: 'sort', order: 'descending' }"
            >
              <el-table-column prop="bus_name" label="商家名称（所属分类）" />
              <el-table-column prop="store_name" label="门店" />
              <el-table-column prop="is_hx" label="是否可核销">
                <template slot-scope="scope">
                  <el-switch v-model="scope.row.is_hx" :active-value="1" :inactive-value="2" />
                </template>
              </el-table-column>
              <el-table-column prop="sort" width="80" label="排序" sortable>
                <template slot-scope="scope">
                  <el-input-number
                    style="width: 100%"
                    size="mini"
                    v-model="scope.row.sort"
                    :controls="false"
                    :precision="0"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="settlement" width="180" label="单次核销结算价格">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.settlement">
                    <el-button
                      size="mini"
                      slot="append"
                      icon="el-icon-edit"
                      @click="
                        setAllAttrsForStoreList({
                          settlement: scope.row.settlement,
                        })
                      "
                    ></el-button>
                  </el-input>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <!-- 可核销商家分类 end -->
          <!-- 用户标签 -->
          <el-form-item label="用户标签">
            <el-select
              filterable
              multiple
              v-model="formFormatData.formData.label"
              placeholder="请选择用户标签"
            >
              <el-option
                v-for="item in userTagList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 用户标签 end -->
          <!-- 是否参与分销 -->
          <el-form-item label="是否参与分销">
            <el-switch
              v-model="formFormatData.formData.is_dealer"
              :active-value="1"
              :inactive-value="2"
            ></el-switch>
          </el-form-item>
          <!-- 是否参与分销 end -->
          <!-- 佣金设置 -->
          <template v-if="formFormatData.formData.is_dealer == 1">
            <el-form-item label="一级分销佣金" prop="commission_1">
              <el-row :gutter="4">
                <el-col style="width: auto">
                  <el-input-number
                    v-model="formFormatData.formData.commission_1"
                    :controls="false"
                    :precision="2"
                    :min="0"
                  ></el-input-number>
                </el-col>
                <el-col style="width: auto">
                  <span v-if="formFormatData.formData.type == 1">元</span>
                  <span v-else-if="formFormatData.formData.type == 2">%</span>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="二级分销佣金" prop="commission_2">
              <el-row :gutter="2">
                <el-col style="width: auto">
                  <el-input-number
                    v-model="formFormatData.formData.commission_2"
                    :controls="false"
                    :precision="2"
                    :min="0"
                  ></el-input-number>
                </el-col>
                <el-col style="width: auto">
                  <span v-if="formFormatData.formData.type == 1">元</span>
                  <span v-else-if="formFormatData.formData.type == 2">%</span>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="三级分销佣金" prop="commission_3">
              <el-row :gutter="2">
                <el-col style="width: auto">
                  <el-input-number
                    v-model="formFormatData.formData.commission_3"
                    :controls="false"
                    :precision="2"
                    :min="0"
                  ></el-input-number>
                </el-col>
                <el-col style="width: auto">
                  <span v-if="formFormatData.formData.type == 1">元</span>
                  <span v-else-if="formFormatData.formData.type == 2">%</span>
                </el-col>
              </el-row>
            </el-form-item>
          </template>
          <!-- 佣金设置 end -->
          <!-- 购买赠送优惠券 -->
          <el-form-item label="购买赠送优惠券">
            <el-select
              filterable
              multiple
              v-model="formFormatData.formData.coupon"
              placeholder="请选择购买赠送优惠券"
            >
              <el-option
                v-for="item in couponList"
                :key="item.coupon_id"
                :label="item.name"
                :value="item.coupon_id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 购买赠送优惠券 end -->
        </el-form>
      </div>
    </div>
    <!-- footer -->
    <div v-cloak class="wlm-fixed-btn flex-row flex-align-c flex-justify-c">
      <el-button
        size="small"
        @click="
          formFormatSubmit({
            router: { type: 'replace', path: '/application/cardBag', code: 1 },
          })
        "
        type="primary"
      >保存</el-button>
      <router-link tag="span" to="/application/cardBag">
        <el-button size="small">返回</el-button>
      </router-link>
    </div>
    <!-- footer end -->
  </div>
</template>

<script>
import fp from "lodash/fp";
import {
  cardBagDetail,
  cardAddEdit,
  cardIndex,
  getStoreForSortId
} from "@/api/cardBag";
import { getUserTag, couponList } from "@/api/application";
import { getSort } from "@/api/merchant";
import ChooseFiles from "@/components/ChooseFiles/index";
import ChooseCoupon from "@/components/ChooseCoupon/index";
import ueditor from "@/components/Ueditor/index";
import mixins from "@/mixins/mixins";
export default {
  mixins: [mixins.getters("Form")],
  components: {
    ChooseFiles,
    ChooseCoupon,
    ueditor
  },
  data() {
    return {
      isEdit: false,
      // 商家门店的数据（一次性取出所有 前端限制高度 滚动浏览）
      storeList: [],
      // 可核销商家分类列表数据
      cusinessCateList: [],
      // 优惠券列表数据
      couponList: [],
      // 用户标签列表数据
      userTagList: [],
      // 卡包分类列表数据
      cardBagCateList: [],
      // 富文本编辑器的一个东西
      ueditorList: [],
      // 卡包logo图
      chooseLogoIdformConfig: {
        type: ["image"],
        model: "display",
        uploadConfig: {
          limit: 1,
          isMore: true,
          model: "display"
        },
        isUnique: false, //在图片选择器中是否多选
        initList: [],
        isShowList: true,
        file_type: "image",
        bindKey: {
          key: "logo",
          model: "img"
        }
      },
      // 卡包封面图配置
      chooseImageIdformConfig: {
        type: ["image"],
        model: "display",
        uploadConfig: {
          limit: 1,
          isMore: true,
          model: "display"
        },
        isUnique: false, //在图片选择器中是否多选
        initList: [],
        isShowList: true,
        file_type: "image",
        bindKey: {
          key: "image_id",
          model: "img"
        }
      },
      // 选择优惠券的配置
      chooseCouponConfig: {
        type: ["chooseCoupon"],
        model: "display",
        get_limit_type: 0,
        disabled: [
          {
            label: "status",
            value: 1,
            reverse: true
          },
          {
            label: "get_limit_type",
            value: 1
          },
          {
            label: "coupon_type",
            value: 40
          }
        ],
        initList: []
      },
      // 当前选中的优惠券的数据

      // 表单相关配置
      formFormatData: {
        key: "cardBagSetting",
        api: {
          editForm: {
            api: cardBagDetail,
            params: {
              id: this.$route.query.id
            },
            redirect: "id",
            filters: {
              img: {
                bindInit: ["chooseImageIdformConfig"]
              }
            }
          },
          submitForm: cardAddEdit
        },
        formData: {
          // 卡包分类
          card_class_id: "",
          // 卡包封面图
          image_id: [],
          // 次数类型 次数类型（1：固定次数，2：任意次数）
          type: 2,
          // 可核销次数
          number: 1,
          // 卡包名称
          title: "",
          // 每几天
          day: 0,
          // 几次
          day_number: 0,
          // 未达限制是否扣次 1：扣，2：不扣
          is_sub: 1,
          // 单次售卖价格
          unit_price: 1,
          // 卡券详情
          content: "",
          // 可核销商家分类
          business_class_ids: [],
          // 用户标签
          label: [],
          // 是否参与分销 1：是，2：否
          is_dealer: 1,
          // 一级分销佣金
          commission_1: 0,
          // 二级分销佣金
          commission_2: 0,
          // 三级分销佣金
          commission_3: 0,
          // 优惠券
          coupon: []
        }
      }
    };
  },
  computed: {
    // 最终要保存的数据
    cDataToSave() {
      const source = this.formFormatData.formData || {};
      let data = {};
      data = fp.set("business", this.storeList, source);
      return data;
    },
    // 表单的校验规则
    cFormRules() {
      return {
        card_class_id: [
          {
            required: true,
            message: "请选择卡包分类",
            trigger: "change"
          }
        ],
        image_id: [
          {
            type: "array",
            required: true,
            message: "请选择卡包封面图",
            trigger: "change"
          }
        ],
        number: [
          {
            required: this.cDataToSave.type == 1,
            message: "请填写可核销次数",
            trigger: "change"
          }
        ],
        title: [
          {
            required: true,
            message: "请填写卡包名称",
            trigger: "change"
          }
        ],
        day: [
          {
            required: true,
            message: "必填",
            trigger: "change"
          }
        ],
        day_number: [
          {
            required: true,
            message: "必填",
            trigger: "change"
          }
        ],
        unit_price: [
          {
            required: true,
            message: "必填",
            trigger: "change"
          }
        ],
        content: [
          {
            required: true,
            message: "请填写卡券详情",
            trigger: "change"
          }
        ],
        business_class_ids: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个可核销商家分类",
            trigger: "change"
          }
        ],
        commission_1: [
          {
            required: this.cDataToSave.is_dealer == 1,
            message: "必填",
            trigger: "change"
          }
        ],
        commission_2: [
          {
            required: this.cDataToSave.is_dealer == 1,
            message: "必填",
            trigger: "change"
          }
        ],
        commission_3: [
          {
            required: this.cDataToSave.is_dealer == 1,
            message: "必填",
            trigger: "change"
          }
        ],
        business: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个门店",
            trigger: "change"
          },
          {
          validator: (rule, value, callback) => {
            if(fp.flowRight(fp.find(bus=>bus.settlement > this.cDataToSave.unit_price),fp.get('business'))(this.cDataToSave)) {
              callback(new Error('结算价非法'))
            }else {
              callback()
            }
            
          }
        }
        ],
        settlement: []
      };
    }
  },
  watch: {
    "formFormatData.formData.business_class_ids"(val) {
      this.fetchStoreList({
        sort_id: val
      });
    }
  },
  created() {
    // 请求表单数据
    // cardBagDetail()
    if (this.$route.query.card_id) {
      this.isEdit = true
      cardBagDetail({
        card_id: this.$route.query.card_id
      }).then(res => {
        const data = fp.get("data.data", res) || {};
        this.formFormatData.formData = data;
        this.chooseImageIdformConfig.initList = data.image_id || [];
        this.chooseLogoIdformConfig.initList = data.logo || [];
        this.storeList = data.business || [];
      });
    }
    this.fetchCardBagCateList();
    this.fetchUserTagList();
    this.fetchCouponList();
    this.fetchBusinessCateList();
  },
  methods: {
    getFormFormatData() {
      return this.cDataToSave;
    },
    // 设置StoreList，比如统一修改单次核销结算价格
    setAllAttrsForStoreList(attrs = {}) {
      this.storeList = fp.map(
        item => ({
          ...item,
          ...attrs
        }),
        this.storeList
      );
    },
    // 根据参数请求商家门店的数据
    fetchStoreList({ sort_id } = {}) {
      const newSortId =
        sort_id ||
        fp.get("formData.business_class_ids", this.formFormatData) ||
        [];
      if (!fp.size(newSortId)) {
        this.storeList = [];
        return;
      }
      getStoreForSortId({
        sort_id: newSortId,
        page: 1,
        list_rows: 1000
      }).then(res => {
        this.storeList = fp.flowRight(
          fp.map(item => {
            return {
              ...item,
              // 是否可核销
              is_hx:
                fp.flowRight(
                  fp.get("is_hx"),
                  fp.find(business => business.store_id === item.store_id),
                  fp.get("formData.business")
                )(this.formFormatData) || 1,
              // 排序
              sort: 1,
              // 结算单价
              settlement:
                fp.flowRight(
                  fp.get("settlement"),
                  item=>{
                    console.log('haha',item)
                    return item
                  },
                  fp.find(business => business.store_id === item.store_id),
                  item=>{
                    console.log('yaya',item)
                    return item
                  },
                  fp.get("formData.business")
                )(this.formFormatData) || 0
            };
          }),
          fp.get("data.data")
        )(res);
        console.log("fetchBusinessCateList res", res);
      });
    },
    // 请求可核销商家分类列表数据
    fetchBusinessCateList() {
      getSort().then(res => {
        this.cusinessCateList = fp.get("data.data", res);
        console.log("fetchBusinessCateList res", res);
      });
    },
    // 请求用户标签列表数据
    fetchCouponList() {
      couponList({
        page: 1,
        list_rows: 1000
      }).then(res => {
        this.couponList = fp.get("data.data.data", res);
        console.log("fetchCouponList res", res);
      });
    },
    // 请求卡包分类列表数据
    fetchCardBagCateList() {
      cardIndex({
        page: 1,
        list_rows: 1000
      }).then(res => {
        this.cardBagCateList = fp.get("data.data.data", res);
        console.log("fetchCardBagCateList res", res);
      });
    },
    // 请求用户标签列表数据
    fetchUserTagList() {
      getUserTag({
        page: 1,
        list_rows: 1000
      }).then(res => {
        this.userTagList = fp.get("data.data", res);
        console.log("fetchUserTagList res", res);
      });
    },
    ueditorChange(msg) {
      this.formFormatData.formData.content = msg;
    },
    couponToogle() {
      this.$refs.chooseCoupon.toggle();
    },
    filtersCouponChange(arg) {
      const { displayData } = arg;
      console.log("filtersCouponChange", displayData);
      // this.formFormatData.formData.coupon_name = displayData.map(item=>{item.id})
    }
  }
};
</script>

<style lang="scss" scoped>
</style>